package com.yy.micro.magic.data.provider;

import com.yy.micro.magic.core.provider.impl.CodeMapResourceProvider;
import com.yy.micro.magic.data.domain.CodeItemVo;
import com.yy.micro.magic.data.domain.CodeMapVo;
import com.yy.micro.magic.data.resource.CodeMapResource;
import com.yy.micro.magic.ext.domain.code.CodeMapItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Optional;

@Component
public class DataCodeMapResourceProvider extends CodeMapResourceProvider {

    @Autowired
    private CodeMapResource resource;

    @Override
    public CodeMapItem findCodeMapItem(final String planCode, final String codeName, final Object value) {
        CodeMapVo vo= resource.load(codeName);
        Assert.notNull(vo,"not find code map by code name "+codeName);
        Assert.notEmpty(vo.getItems(),"code["+codeName+"] table item is empty.");
        Optional<CodeItemVo> item =vo.getItems().stream().filter(v->v.getSrcValue().equals(value)).findFirst();
        if (item.isPresent()){
            return item.get().toDomain();
        }
        return null;
    }

    @Override
    public Object findCodeTargetValue(final String planCode, final String codeName, final Object value) {
        CodeMapItem item = findCodeMapItem(planCode,codeName,value);
        Assert.notNull(item,"Not find code item by code name["+codeName+"] and value["+value+"].");
        return item.getTargetValue();
    }
}
